package com.gujiayue.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

	/**
	 * JSON转对象
	 * @param obj 转成对象
	 * @param jsonStr json字符
	 * @return
	 */
	public static Object contraryJson(Object obj, String jsonStr) {
		ObjectMapper mapper = new ObjectMapper();
		//字段 反序列化 不存在问题
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		try {
			return mapper.readValue(jsonStr, obj.getClass());
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (JsonProcessingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 对象转JSON
	 * @param obj 待转换对象
	 * @return
	 */
	public static String obeyJson(Object obj) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			return mapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			// e.printStackTrace();
			return null;
		}
	}

}
